package com.kim.smartring.adapter;

import java.util.HashMap;
import java.util.Locale;
import java.util.UUID;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kim.smartring.R;
import com.kim.smartring.ble.BleNamesResolver;
import com.kim.smartring.ble.BleWrapper;

public class DemoCharacteristicDetailsAdapter extends BaseAdapter {

	private static final String TAG = "DemoCharacteristicDetailsAdapter";
	private HashMap<String, Integer> checkedState = new HashMap<String, Integer>();

	private BluetoothGattCharacteristic mCharacteristic = null;
	private LayoutInflater mInflater;
	private BleWrapper mBleWrapper = null;
	private byte[] mRawValue = null;
	private int mIntValue = 0;
	private String mAsciiValue = "";
	private String mStrValue = "";
	private String mLastUpdateTime = "";
	private boolean mNotificationEnabled = false;

	public DemoCharacteristicDetailsAdapter(Context context, BleWrapper ble) {
		super();
		mBleWrapper = ble;
		mInflater = LayoutInflater.from(context);
	}

	public void setCharacteristic(BluetoothGattCharacteristic ch) {
		this.mCharacteristic = ch;
		mRawValue = null;
		mIntValue = 0;
		mAsciiValue = "";
		mStrValue = "";
		mLastUpdateTime = "-";
		mNotificationEnabled = false;
	}

	public BluetoothGattCharacteristic getCharacteristic(int index) {
		return mCharacteristic;
	}

	public void clearCharacteristic() {
		mCharacteristic = null;
	}

	@Override
	public int getCount() {
		return (mCharacteristic != null) ? 1 : 0;
	}

	@Override
	public Object getItem(int position) {
		return mCharacteristic;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void newValueForCharacteristic(final BluetoothGattCharacteristic ch,
			final String strVal, final int intVal, final byte[] rawValue,
			final String timestamp) {
		if (!ch.equals(this.mCharacteristic))
			return;
		
		Log.d(TAG, "rawValue" + rawValue.toString());

		mIntValue = intVal;
		mStrValue = strVal;
		mRawValue = rawValue;
		if (mRawValue != null && mRawValue.length > 0) {
			final StringBuilder stringBuilder = new StringBuilder(
					mRawValue.length);
			for (byte byteChar : mRawValue)
				stringBuilder.append(String.format("%02X", byteChar));
			mAsciiValue = "0x" + stringBuilder.toString();
		} else
			mAsciiValue = "read nothing.";

		String uuid = ch.getUuid().toString();
		if (BleNamesResolver.UUID_C_STEP.equals(uuid)) { // 读取记步数据
			try {
				int steps = mRawValue[0] + ((int) (mRawValue[1]) << 8)
						+ ((int) mRawValue[2] << 16)
						+ ((int) mRawValue[3] << 24);
				int distance = mRawValue[4] + ((int) (mRawValue[5]) << 8)
						+ ((int) mRawValue[6] << 16)
						+ ((int) mRawValue[7] << 24);
				int calories = mRawValue[8] + ((int) (mRawValue[9]) << 8)
						+ ((int) mRawValue[10] << 16)
						+ ((int) mRawValue[11] << 24);
				Log.d(TAG, String.format(
						"StepInfo--->steps:%sdistance:%scalories:%s", steps,
						distance, calories));
				mAsciiValue = String.format(
						"Step count:%s \nDistance:%s \nCalories:%s", steps,
						distance, calories);
			} catch (Exception e) {
				Log.d(TAG, e.getMessage());
			}
		} else if (BleNamesResolver.UUID_C_SLEEP.equals(uuid)) { // 读取睡眠数据

			try {
				int sleep = ((int) (mRawValue[1]))
						+ ((int) (mRawValue[2] << 8));
				mAsciiValue = String.format("Sleep Info:%s", sleep);
			} catch (Exception e) {
				Log.d(TAG, e.getMessage());
			}

		} else if (BleNamesResolver.UUID_C_HR.equals(uuid)) { // 读取心率数据
			try {
				int hrFlag = ((int) (mRawValue[0]));
				if (hrFlag != 0) {
					mAsciiValue = "unKnow";
					//return;
				}
				int hrValue = 0;
				if(mRawValue.length ==1){
					hrValue = ((int) (mRawValue[0]));
				}else{
					hrValue = ((int) (mRawValue[1]));
				}
				mAsciiValue = String.format("Heart Rate:%s", hrValue);
			} catch (Exception e) {
				Log.d(TAG, e.getMessage());
			}

		} else {
		}

		Log.d(TAG, "data notify:" + mAsciiValue);
		mLastUpdateTime = timestamp;
		if (mLastUpdateTime == null)
			mLastUpdateTime = "";
	}

	public void setNotificationEnabledForService(
			final BluetoothGattCharacteristic ch) {
		if ((!ch.equals(this.mCharacteristic))
				|| (mNotificationEnabled == true))
			return;
		mNotificationEnabled = true;
		notifyDataSetChanged();
	}

	public static int byte4ToInt(byte[] bytes, int off) {
		int b0 = bytes[off] & 0xFF;
		int b1 = bytes[off + 1] & 0xFF;
		int b2 = bytes[off + 2] & 0xFF;
		int b3 = bytes[off + 3] & 0xFF;
		return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
	}

	public byte[] parseHexStringToBytes(final String hex) {
		String tmp = hex.substring(2).replaceAll("[^[0-9][a-f]]", "");
		byte[] bytes = new byte[tmp.length() / 2]; // every two letters in the
													// string are one byte
													// finally

		String part = "";

		for (int i = 0; i < bytes.length; ++i) {
			part = "0x" + tmp.substring(i * 2, i * 2 + 2);
			bytes[i] = Long.decode(part).byteValue();
		}

		return bytes;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup p) {
		// get already available view or create new if necessary
		// TODO 将视图置为null是为了测试
		convertView = null;
		if (convertView == null) {
			convertView = mInflater
					.inflate(
							R.layout.demo_item_periphera_devicel_characteristic_details,
							null);
		}

		ImageView imageView = (ImageView) convertView
				.findViewById(R.id.img_data_type);
		TextView txtValue = null;
		LinearLayout layout = null;

		String uuid = mCharacteristic.getUuid().toString()
				.toLowerCase(Locale.getDefault());
		if (BleNamesResolver.UUID_C_STEP.equals(uuid)) { // 读取记步数据
			imageView.setBackgroundResource(R.drawable.selector_step);
			txtValue = (TextView) convertView.findViewById(R.id.txt_step_count);
			layout = (LinearLayout) convertView.findViewById(R.id.l_step);
		} else if (BleNamesResolver.UUID_C_SLEEP.equals(uuid)) { // 读取睡眠数据
			imageView.setBackgroundResource(R.drawable.selector_sleep);
			txtValue = (TextView) convertView.findViewById(R.id.txt_ssleep);
			layout = (LinearLayout) convertView.findViewById(R.id.l_sleep);
		} else if (BleNamesResolver.UUID_C_HR.equals(uuid)) { // 读取心率数据
			imageView.setBackgroundResource(R.drawable.selector_hrate);
			txtValue = (TextView) convertView.findViewById(R.id.txt_hreate);
			layout = (LinearLayout) convertView.findViewById(R.id.l_hrate);
		} else {
			return convertView;
		}
		layout.setVisibility(View.VISIBLE);

		// 读取数据
		// mBleWrapper.requestCharacteristicValue(mCharacteristic);

		int format = mBleWrapper.getValueFormat(mCharacteristic);
		int props = mCharacteristic.getProperties();
		String propertiesString = String.format("0x%04X [", props);
		if ((props & BluetoothGattCharacteristic.PROPERTY_READ) != 0)
			propertiesString += "read ";
		if ((props & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0)
			propertiesString += "write ";
		if ((props & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0)
			propertiesString += "notify ";
		if ((props & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0)
			propertiesString += "indicate ";
		if ((props & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0)
			propertiesString += "write_no_response ";

		String tmp = mCharacteristic.getService().getUuid().toString()
				.toLowerCase(Locale.getDefault());
		String cName = BleNamesResolver.resolveServiceName(tmp);
		Log.d(TAG, "Characteristic Name : " + cName);

		if ((props & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0
				&& (checkedState.get(uuid) == null || checkedState.get(uuid) != 1)
				&& !BleNamesResolver.UUID_C_HR.equals(uuid)) {
			mBleWrapper.setNotificationForCharacteristic(mCharacteristic, true);
			checkedState.put(uuid, 1);
			Log.d(TAG, "set notify enable.");
		} else if (BleNamesResolver.UUID_C_HR.equals(uuid)) {
			final Button btnStart = (Button) convertView
					.findViewById(R.id.btn_start);
			final Button btnStop = (Button) convertView
					.findViewById(R.id.btn_stop);
			btnStart.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					for(int i=0;i<5;i++){
						mBleWrapper.setNotificationForCharacteristic(
								mCharacteristic, true);
						try{
							Thread.sleep(100);Thread.sleep(100);
						}catch(Exception e){
							
						}
						
					}
					mBleWrapper.setNotificationForCharacteristic(
							mCharacteristic, true);
					String newValue = "0x01";
					final byte[] dataToWrite = parseHexStringToBytes(newValue);
					Log.d("sendData", "sendData:" + dataToWrite.toString());
					final BluetoothGattCharacteristic bluetoothGattCharacteristic = mCharacteristic
							.getService()
							.getCharacteristic(
									UUID.fromString(BleNamesResolver.UUID_C_HR_SETTINGS));
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
//							mBleWrapper.writeDataToCharacteristic(
//									bluetoothGattCharacteristic, dataToWrite);
						}
					}, 200);
					btnStart.setEnabled(false);
					btnStop.setEnabled(true);
				}
			});

			btnStop.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mBleWrapper.setNotificationForCharacteristic(
							mCharacteristic, false);
					String newValue = "0x00";
					final byte[] dataToWrite = parseHexStringToBytes(newValue);
					Log.d("sendData", "sendData:" + dataToWrite.toString());
					final BluetoothGattCharacteristic bluetoothGattCharacteristic = mCharacteristic
							.getService()
							.getCharacteristic(
									UUID.fromString(BleNamesResolver.UUID_C_HR_SETTINGS));
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
//							mBleWrapper.writeDataToCharacteristic(
//									bluetoothGattCharacteristic, dataToWrite);
						}
					}, 200);
					btnStop.setEnabled(false);
					btnStart.setEnabled(true);
				}
			});
		} else {
			mBleWrapper.requestCharacteristicValue(mCharacteristic);
		}
		Log.d(TAG, "value:" + mAsciiValue);
		Log.d(TAG, "mStrValue:" + mStrValue);
		Log.d(TAG, "mIntValue:" + mIntValue);

		if (BleNamesResolver.UUID_C_STEP.equals(uuid)) { // 读取记步数据
			txtValue.setText("" + mAsciiValue);
		} else if (BleNamesResolver.UUID_C_SLEEP.equals(uuid)) { // 读取睡眠数据
			txtValue.setText("" + mAsciiValue);
		} else if (BleNamesResolver.UUID_C_HR.equals(uuid)) { // 读取心率数据
			txtValue.setText("" + mAsciiValue);
		} else {
			return convertView;
		}
		return convertView;
	}
}